import { RouteObject, useRoutes } from 'react-router-dom'
import Login from "@/pages/Login";
import { lazy, Suspense } from 'react';
import { Spin } from 'antd'
import Layout from '@/Layout';


const DashBoard = lazy(() => import('@/pages/DashBoard'));

interface RouteItem {
  path: string;
  component: JSX.Element;
  children?: RouteItem[];
  isLazy?: boolean;
  fold?: boolean;
}

const routes: RouteItem[] = [
  {
    path: '/login',
    component: <Login/>
  },
  {
    path: '/',
    component: <Layout />,
    children: [
      {
        path: '/',
        component: <DashBoard/>,
        isLazy: true
      },
    ]
  }
];

const generateRoutes = (routes: RouteItem[]): RouteObject[] => {
  let routerTable: RouteObject[] = [];

  routes.forEach(route => {
    let element;
    if(route.fold){
      element = <Layout />
    }else{
      element = route.isLazy ? <Suspense fallback={<Spin spinning={true} />} >{route.component}</Suspense> : route.component;
    }
    
    routerTable.push({
      path: route.path,
      element: element,
      children: route.children ? generateRoutes(route.children) : undefined,
    })
  })

  return routerTable;
};

export default function createRouter() {
  return useRoutes(generateRoutes(routes));
}